package LeetCode.leetcode43;

class Solution {
    public static void main(String[] args) {
        System.out.println(new Solution().multiply("123","456"));
        System.out.println(new Solution().test("123","456"));
    }
    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        int[] res = new int[num1.length() + num2.length()];
        for (int i = num1.length() - 1; i >= 0; i--) {
            int n1 = num1.charAt(i) - '0';
            for (int j = num2.length() - 1; j >= 0; j--) {
                int n2 = num2.charAt(j) - '0';
                int sum = (res[i + j + 1] + n1 * n2);
                res[i + j + 1] = sum % 10;
                res[i + j] += sum / 10;
            }
        }

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < res.length; i++) {
            if (i == 0 && res[i] == 0) continue;
            result.append(res[i]);
        }
        return result.toString();
    }
    public String test(String num1, String num2) {
        int m = num1.length();
        int n = num2.length();
        int[] pos = new int[m+n];
        for (int i = m - 1; i >= 0 ; i--) {
            for (int j = n - 1; j >= 0; j--) {
                int q = i + j + 1;
                int w = i + j;
                int x = (num1.charAt(i) - '0') * (num2.charAt(j) - '0') + pos[q];
                pos[q] = x % 10;
                pos[w] += x / 10;
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < pos.length; i++) {
            if (sb.length() == 0 && pos[i] == 0) continue;
            sb.append(pos[i]);
        }
        return  new String(sb);
    }
}